import 'package:flutter/material.dart';
import 'package:flutter_base/bean/home/home_article_list_entity.dart';
import 'package:flutter_base/page/common/smart_refresh_widget.dart';
import 'package:flutter_base/page/common/webview_page.dart';
import 'package:flutter_base/page/common/webview_widget.dart';
import 'package:flutter_base/viewmodel/home/home_vm.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../utils/navigator_utils.dart';

///
/// @DIR_PATH：lib/page/home
/// @TIME：2024/5/3 7:39
/// @AUTHOR：starr
///
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin{
  HomeViewModel homeViewModel = HomeViewModel();
  RefreshController refreshController = RefreshController(); //下拉刷新控制器

  @override
  void initState() {
    super.initState();
    homeViewModel.getBannerData();
    homeViewModel.initHomeListData(false);
  }


  refreshOrLoadMore(bool loadMore) {
    homeViewModel.initHomeListData(loadMore, callback: (loadMore) {
      if (loadMore) {
        refreshController.loadComplete();
      } else {
        refreshController.refreshCompleted();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<HomeViewModel>(
        create: (context) => homeViewModel,
        child: SafeArea(
            child: SmartRefreshWidget(
          controller: refreshController,
          onLoading: () {
            //下拉加载
            refreshOrLoadMore(true);
          },
          onRefresh: () {
            //下拉刷新
            homeViewModel.getBannerData().then((value){
              refreshOrLoadMore(false);
            });
          },
          child: SingleChildScrollView(
            child: Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  //第一部分：banner
                  _banner(),
                  //第二部分：ListView
                  _listView(),
                ]),
          ),
        )));
  }

  Widget _listView() {
    return Consumer<HomeViewModel>(builder: (context, vm, child) {
      return ListView.builder(
          itemBuilder: (context, index) {
            return _listItemView(vm.homeList?[index],index);
          },
          // 优化
          shrinkWrap: true,
          // 禁止滑动
          physics: const NeverScrollableScrollPhysics(),
          itemCount: vm.homeList?.length ?? 0);
    });
  }

  Widget _listItemView(HomeArticleListDatas? itemData, int index) {
    var name;
    if (itemData?.author?.isNotEmpty == true) {
      name = itemData?.author ?? "";
    } else {
      name = itemData?.shareUser ?? "";
    }
    return GestureDetector(
      onTap: () {
        NavigatorUtils.pushPage(
            context,
            WebViewPage(
              webViewType: WebViewType.URL,
              loadResource: itemData?.link ?? "",
              title: itemData?.title,
              showTitle: true,
            ));
      },
      child: Container(
          margin: const EdgeInsets.all(10),
          padding: EdgeInsets.all(10),
          decoration: BoxDecoration(
            borderRadius: const BorderRadius.all(Radius.circular(10)),
            border: Border.all(
              color: Colors.grey,
              width: 0.5,
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(20),
                    child: Image.asset(
                      "assets/images/2.0x/app_icon.png",
                      width: 40,
                      height: 40,
                      fit: BoxFit.fill,
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 10),
                    child: Text(name,
                        style: TextStyle(fontSize: 15, color: Colors.black)),
                  ),
                  Expanded(child: SizedBox()),
                  Padding(
                    padding: EdgeInsets.only(right: 10),
                    child: Text(itemData?.niceShareDate ?? "",
                        style: const TextStyle(fontSize: 14, color: Colors.black)),
                  ),
                  (itemData?.type.toInt() == 1)
                      ? const Text("置顶",
                          style: TextStyle(
                              fontSize: 15,
                              color: Colors.blue,
                              fontWeight: FontWeight.bold))
                      : const SizedBox(),
                ],
              ),
              Padding(
                padding: EdgeInsets.only(top: 10),
                child: Text(itemData?.title ?? "",
                    style: TextStyle(fontSize: 18, color: Colors.black)),
              ),
              Row(
                children: [
                  Text(itemData?.chapterName ?? "",
                      style: TextStyle(
                          fontSize: 12,
                          color: Colors.blue,
                          fontWeight: FontWeight.bold)),
                  Expanded(child: SizedBox()),
                  GestureDetector(
                    onTap: (){
                      if(itemData?.collect == true){
                        homeViewModel.unCollect("${itemData?.id}",index).then((value){
                          if(value == true){
                            showToast("取消收藏");
                          }
                        });
                      }else{
                        homeViewModel.collect("${itemData?.id}",index).then((value) {
                          if(value == true){
                            showToast("收藏成功");
                          }
                        });
                      }
                    },
                    child: Image.asset(
                        itemData?.collect == true ? "assets/images/a/ic_collect.png" : "assets/images/a/ic_uncollect.png" ,
                        width: 35, height: 35),
                  ),
                ],
              )
            ],
          )),
    );
  }

  Widget _banner() {
    return Consumer<HomeViewModel>(builder: (context, vm, child) {
      return Container(
        alignment: Alignment.topCenter,
        height: 200,
        child: Swiper(
          itemCount: vm.bannerList?.length ?? 0,
          indicatorLayout: PageIndicatorLayout.COLOR,
          autoplay: true,
          controller: SwiperController(),
          pagination: const SwiperPagination(),
          itemBuilder: (BuildContext context, int index) {
            return GestureDetector(
              onTap: () {
                NavigatorUtils.pushPage(
                    context,
                    WebViewPage(
                      webViewType: WebViewType.URL,
                      loadResource: vm.bannerList?[index]?.url ?? "",
                      title: vm.bannerList?[index]?.title,
                      showTitle: true,
                    ));
              },
              child: SizedBox(
                height: 200,
                child: Image.network(
                  vm.bannerList?[index]?.imagePath ?? "",
                  fit: BoxFit.fill,
                ),
              ),
            );
          },
        ),
      );
    });
  }

  @override
  bool get wantKeepAlive => true;
}
